﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Data;
using WebAPI存储过程多接口聚合.Models;
using WebAPI存储过程多接口聚合.SQLHelper;

namespace WebAPI存储过程多接口聚合.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class SQLServerController : ControllerBase
    {
        private readonly SQLServerHelper sqlServerHelper;
        public SQLServerController(SQLServerHelper sqlServer)
        {
            this.sqlServerHelper = sqlServer;
        }
        [HttpPost]
        public ActionResult<object> SelectData(DataModel data)
        {
            try
            {
                DataTable dt = sqlServerHelper.ExecuteQuery(data.ProcedureName, data.Json.ToString(),data.DataKey);
                string res = JsonConvert.SerializeObject(dt, Formatting.Indented);
                return Ok(res);
            }
            catch (Exception ex)
            {
                return BadRequest(new { state = 400, msg = ex.Message });
            }

        }

        [HttpPost]
        public ActionResult<object> ModifyData(DataModel data)
        {
            try
            {
                sqlServerHelper.ExecuteNonQuery(data.ProcedureName, data.Json.ToString(), data.DataKey);
                return Ok(new { state = 200, msg = "成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { state = 400, msg = ex.Message });
            }

        }
    }
}
